//
//  UserAccountViewModel.swift
//  新浪微博
//
//  Created by mac on 15/11/29.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class UserAccountViewModel: NSObject {
    var account: UserAccount?
    
    override init(){
    super.init()
        account = UserAccount.loadAccount()
        
     
    }
    //用户是否登录
    var userLogin: Bool{
//        print(account?.access_token)
    return account?.access_token != nil
    }
    
    var token: String?{
    return account?.access_token
    }
    //用户名的计算属性
    var userName: String? {
    return account?.name
    }
    //用户头像url
    var headImageURL: NSURL?{
    let url = NSURL(string: account?.avatar_large ?? "")
        return url
    }
    //请求用户的TOKEN
        func loadAccessToken(code: String,finished: (error: NSError?)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求需要的参数
        let paramenters = ["client_id" : client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let afn = AFHTTPSessionManager()
        //设置添加反序列户类型
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        afn.POST(urlString, parameters: paramenters, success: { (_, result) -> Void in
            //拿到用户token之后,立即请求用户信息
            guard let dict = result as?[String: AnyObject] else{
                return
            }
            let account = UserAccount(dict: dict)
            print(result)
            //加载用户信息
            self.loadUserInfo(account, finished: finished)
            
           
            }) { (_, error) -> Void in
                finished(error: error)
              
        }
    }
    
    
    
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        //为了保险,先判断
        guard let access_token = account.access_token,userId = account.uid else{
            SVProgressHUD.showErrorWithStatus("获取网络数据失败")
            return
        }
    
        let parameters = ["access_token":access_token,"uid":userId]
        let afn = AFHTTPSessionManager()
        afn .GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            account.avatar_large = result["avatar_large"]as? String
            account.name = result["name"]as? String
            //保存信息
            account.saveAccount()
            finished(error: nil)
            SVProgressHUD.showSuccessWithStatus("登录成功")
            
            }) { (_, error) -> Void in
                finished(error: error)
                print(error)
        }
        
    }

}
